package com.rd.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rd.common.vo.AdminStatusVO;
import com.rd.common.vo.UpdateAvatarFormData;
import com.rd.common.vo.UpdatePwdFormData;
import com.rd.pojo.Admin;
import com.rd.pojo.AdminRole;
import com.rd.service.IAdminRoleService;
import com.rd.service.IAdminService;
import com.rd.service.IRoleService;
import com.rd.util.QiniuOssUtil;
import com.rd.util.ResultModel;
import com.rd.util.UploadUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  系统账号管理
 * </p>
 * 请求路径要参考t_menu中url，因为spring security中进行比较
 */
@Slf4j
@RestController
@RequestMapping("/system/admin")
public class AdminController {

    @Autowired
    private IAdminService adminService;
    @Autowired
    private IRoleService roleService;

    @ApiOperation(value = "获取所有账号")
    @GetMapping("/adminList")
    public ResultModel getAllAdmins(String keywords){
        return adminService.getAllAdmins(keywords);
    }

    @ApiOperation(value = "更新账号信息")
    @PostMapping("/updateAdmin")
    public ResultModel updateAdmin(@RequestBody AdminStatusVO adminStatusVO){
        return adminService.updateStatusById(adminStatusVO);
    }

    @Resource
    IAdminRoleService adminRoleService;

    @ApiOperation(value = "删除账号")
    @GetMapping("/deleteAdmin/{id}")
    public ResultModel deleteAdmin(@PathVariable Integer id){
        List<AdminRole> list =
                adminRoleService.list(new QueryWrapper<AdminRole>().eq("adminId", id));
        if(list!=null && list.size()>0){
            return ResultModel.createByErrorCodeMessage("删除失败，此用户拥有角色！");
        }
        if(adminService.removeById(id)){
            return ResultModel.createBySuccess("删除成功！");
        }
        return ResultModel.createByErrorCodeMessage("删除失败！");
    }

    @ApiOperation(value = "获取所有角色")
    @GetMapping("/roleList")
    public ResultModel getAllRoles(){
        return ResultModel.createBySuccess().put("roleList",roleService.list());
    }

    @ApiOperation(value = "更新用户的角色")
    @PostMapping("/updateAdminRole")
    public ResultModel updateAdminRole(Integer adminId,Integer[] rids){
        return adminService.updateAdminRole(adminId,rids);
    }

    /*个人中心相关接口*/
    @ApiOperation(value = "更新信息")
    @PostMapping("/updateAdminInfo")
    public  ResultModel updateAdminInfo(@RequestBody Admin admin){
        return  adminService.updateAdminInfo(admin);
    }
    @ApiOperation(value = "查询旧密码")
    @GetMapping("/checkOldPwd/{userId}/{oldPassword}")
    public  ResultModel checkOldPwd(@PathVariable("userId") Integer userId,@PathVariable("oldPassword") String oldPassword){
        return  adminService.checkOldPwd(userId, oldPassword);
    }
    @ApiOperation(value = "更改密码操作")
    @PostMapping("/updatePwd")
    public ResultModel updatePwd(@RequestBody UpdatePwdFormData pwdForm) {
        int n = adminService.updatePwd(pwdForm);
        return n > 0 ? ResultModel.createBySuccess("修改成功!") : ResultModel.createByErrorCodeMessage("修改失败!");
    }
    @ApiOperation(value = "上传图片")
    @PostMapping("/uploadImage")
    public ResultModel uploadImage(MultipartFile file) throws FileNotFoundException {
        if (Objects.nonNull(file)) {
            //如果上传目录为/static/images/upload/，则可以如下获取：
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) {
                path = new File("");
            }
            System.out.println("path:" + path.getAbsolutePath());
            File dir = new File(path.getAbsolutePath(), "static/images/upload/");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            System.out.println("upload url:" + dir.getAbsolutePath());
            File destFile = new File(dir, UploadUtil.saveFile(file, dir.getAbsolutePath()));
            String qiNiuPath = new QiniuOssUtil().upload(destFile);
            //向前端传递值
            HashMap<String, Object> map = new HashMap<>();
            map.put("code", 0);
            map.put("msg", "图片上传成功!");
            map.put("qiNiuPath", qiNiuPath);
            log.info("上传成功以后的地址：{}", qiNiuPath);
            return ResultModel.createBySuccess(map);
        }
        return ResultModel.createByErrorCodeMessage(-1, "文件上传失败!");
    }

    @ApiOperation(value = "更新头像")
    @PostMapping("/updateAvatar")
    public ResultModel updateAvatar(@RequestBody UpdateAvatarFormData ImgForm) {
        int n = adminService.updateAvatar(ImgForm);
        return n > 0 ? ResultModel.createBySuccess("更新成功!") : ResultModel.createByErrorCodeMessage("更新失败!");
    }




}
